from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication
from django.shortcuts import get_object_or_404

from users.models import UserFavoriteProblem
from problems.models.problem_model import ProblemModel
from weiwenhai_Oj.utils.global_functions import returnResponse
from weiwenhai_Oj.deprecated.handle_exceptions import handle_exceptions


class FavoriteController(viewsets.ViewSet):
    """
    用户收藏控制器
    """
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    @action(methods=['post'], detail=False)
    @handle_exceptions
    def add_favorite(self, request):
        """
        添加收藏
        """
        problem_id = request.data.get('problem_id')
        notes = request.data.get('notes', '')

        if not problem_id:
            return returnResponse(msg="请提供题目ID", status=status.HTTP_400_BAD_REQUEST)

        problem = get_object_or_404(ProblemModel, id=problem_id)
        
        # 检查是否已经收藏
        favorite, created = UserFavoriteProblem.objects.get_or_create(
            user=request.user,
            problem=problem,
            defaults={'notes': notes}
        )

        if not created:
            return returnResponse({
                'code': 400,
                'msg': '已经收藏过了',
            })

        return returnResponse({
            'code': 200,
            'msg': '收藏成功',
        })

    @action(methods=['delete'], detail=False)
    @handle_exceptions
    def remove_favorite(self, request):
        """
        取消收藏
        """
        problem_id = request.query_params.get('problem_id')
        
        if not problem_id:
            return returnResponse({
                'code': 400,
                'msg': '请提供题目ID',
            })

        try:
            favorite = UserFavoriteProblem.objects.get(
                user=request.user,
                problem_id=problem_id
            )
            favorite.delete()
            return returnResponse({ 'code': 200, 'msg': '取消收藏成功' })
        except UserFavoriteProblem.DoesNotExist:
            return returnResponse({
                'code': 400,
                'msg': '未收藏过',
            })

    @action(methods=['get'], detail=False)
    @handle_exceptions
    def list_favorites(self, request):
        """
        获取收藏列表
        """
        favorites = UserFavoriteProblem.objects.filter(user=request.user).select_related('problem')
        
        data = [{
            'id': fav.id,
            'problem_id': fav.problem.id,
            'title': fav.problem.title,
            'difficulty': fav.problem.difficulty,
            'notes': fav.notes,
            'created_time': fav.created_time
        } for fav in favorites]

        return returnResponse(data)

    @action(methods=['put'], detail=False)
    @handle_exceptions
    def update_notes(self, request):
        """
        更新收藏笔记
        """
        problem_id = request.data.get('problem_id')
        notes = request.data.get('notes', '')

        if not problem_id:
            return returnResponse()

        try:
            favorite = UserFavoriteProblem.objects.get(
                user=request.user,
                problem_id=problem_id
            )
            favorite.notes = notes
            favorite.save()
            return returnResponse()
        except UserFavoriteProblem.DoesNotExist:
            return returnResponse()
